#! /bin/python3

import re
import os
import time
from concurrent.futures import ThreadPoolExecutor

test_list = []
name_list = []
status_list = []

def test_check(name):
    log_name = "%s_sim_dir/sim_%s.log"%(name, name)
    file_exist = os.path.isfile(log_name)
    status = "finish"
    if file_exist :
        fd = open(log_name, "r")
        line = fd.readline()
        while line:
            ret = re.search("Passed", line)
            if ret:
                status = "passed"
            else:
                status = "failed"
            line = fd.readline()
        fd.close()
    else :
        status = "failed"
    return status

def run_test(test, name, num):
    status_list[num] = "running"
    os.system("make sim REGRESS=1 %0s "%(test))
    status = test_check(name)
    status_list[num] = status
    return name

def test_done(response):
    dst_fd = open("result_regression.txt", "w")
    dst_fd.write("No,testname,status\n")
    num = 0
    for test_name, status in zip(name_list, status_list):
        num = num + 1
        print("test_name:", test_name, "status:", status)
        dst_fd.write("%03d,%s,%s\n"%(num, test_name, status))
    dst_fd.close()
    # print(response.result(), "finish")    # 即Futuer.result()：取出task的返回值

def run_testsuite(list_file):
    src_fd = open(list_file, "r")
    line = src_fd.readline()
    while(line):
        ret1 = re.match("#?make.+", line)
        if(ret1):
            ret2 = re.search("TESTCASE.+", ret1.group())
            if(ret2):
                ret3 = re.match("TESTCASE=\w+", ret2.group())
                if(ret3):
                    test_list.append(ret2.group())
                    name_list.append(ret3.group()[9:])
                #print(ret2.group())
        line = src_fd.readline()
    print("collect test as this:")
    n = 0
    for name, test in zip(name_list, test_list):
        n = n + 1
        status_list.append("waiting")
        print("%03d, %09s, %-30s: make sim REGRESS=1 %0s"%(n, status_list[n-1], name, test))
    if(os.system("make comp REGRESS=1")):
        print("exit...")
        return -1
    num = 0
    threadpool = ThreadPoolExecutor(2)
    for name, test in zip(name_list, test_list):
        futuer = threadpool.submit(run_test, test, name, num)    # futuer是由task返回的一个Future对象，里面有记录task的返回值
        futuer.add_done_callback(test_done)           # 回调done函数，执行者依然是子线程  
        num = num + 1



if __name__ == "__main__":
    run_testsuite("./runlist")

